import {useEffect, useState} from "react";

interface UseListParams {
    api: (e?: any) => PromiseLike<any>;
    params?: any;
}

interface UseListReturn {
    data: DataProps;
    refresh: () => void;
    pagingChange: (e?: any) => any;
}

export interface DataProps {
    list?: any[];
    current?: number;
    pageNum?: number;
    pageSize?: number;
    total?: number;
}
interface ResProps extends DataProps {
    data: any[];
}

export default function useList({api: fetch, params = {}}: UseListParams, deep: any[] = []): UseListReturn {
    const [data, setData] = useState<DataProps>({});
    const [paging, setPaging] = useState({});

    const handlePagingChange = ({pageSize, current}: DataProps) => {
        setPaging({pageNo: current, pageSize});
    };

    const handleInit = () => {
        fetch({...params, ...paging}).then((res: ResProps) => {
            const {data, pageNum, pageSize, total} = res;
            setData({list: data, current: pageNum, pageNum, pageSize, total});
        });
    };

    useEffect(() => {
        handleInit();
    }, [paging, ...deep]);

    return {data, refresh: handleInit, pagingChange: handlePagingChange};
}
